package config

import (
	"os"
	"strconv"
	"time"

	"github.com/joho/godotenv"
)

// Config 全局配置
type Config struct {
	DBHost    string
	DBPort    string
	DBUser    string
	DBPass    string
	DBName    string
	JWTSecret string // JWT签名密钥
	JWTExpire int64  // 令牌过期时间（秒），建议2小时=7200
	APPEnv    string // 环境
	// RedisConfig Redis连接配置
	RedisAddr     string
	RedisPassword string
	RedisDB       int64
	RedisPoolSize int64
	RedisTimeout  time.Duration
}

// Init 初始化配置（从.env文件加载）
func Init() *Config {
	godotenv.Load() // 加载.env文件

	return &Config{
		DBHost:    getEnv("DB_HOST", "localhost"),
		DBPort:    getEnv("DB_PORT", "3306"),
		DBUser:    getEnv("DB_USER", "root"),
		DBPass:    getEnv("DB_PASS", "123456"),
		DBName:    getEnv("DB_NAME", "app_db"),
		JWTSecret: getEnv("JWT_SECRET", "your-secret-key"), // 生产环境需复杂密钥
		JWTExpire: getEnvInt("JWT_EXPIRE", 7200),
		APPEnv:    getEnv("APPEnv", "dev"),
		// Redis连接配置
		RedisAddr:     getEnv("REDIS_ADDR", "localhost:6379"),
		RedisPassword: getEnv("REDIS_PASSWORD", ""),
		RedisDB:       getEnvInt("REDIS_DB", 0),
		RedisPoolSize: getEnvInt("REDIS_POOLSIZE", 1),
		RedisTimeout:  getEnvTime("REDIS_TIMEOUT"),
	}
}

// 工具函数：获取环境变量，默认值兜底
func getEnv(key, def string) string {
	val := os.Getenv(key)
	if val == "" {
		return def
	}
	return val
}

func getEnvInt(key string, def int64) int64 {
	val := os.Getenv(key)
	if val == "" {
		return def
	}
	res, _ := strconv.ParseInt(val, 10, 64)
	return res
}

func getEnvTime(key string) time.Duration {
	val := os.Getenv(key)
	res, _ := time.ParseDuration(val)
	return res
}
